<?php

namespace App\Modules\Admin\Services\Bus;

use App\Library\Junda\src\Consumption;
use App\Library\Pay\AliPayService;
use App\Library\Wechat\PayWeChatApi;
use App\Modules\Admin\Entities\Member\UserCardModel;
use App\Modules\Admin\Entities\Pay\OrderRefundModel;
use App\Modules\Admin\Entities\Water\WaterCardTransactionModel;
use App\Modules\Admin\Entities\Water\WaterOrderModel;
use App\Modules\Admin\Services\BaseService;
use EasyWeChat\Pay\Application as payApp;

class ConsumeService extends BaseService
{
    public function __construct(WaterOrderModel $model)
    {
        $this->model = $model;
        $this->with =['water_device_info','user_info'];
    }
    public function lists(array $params) : array
    {
        $params['where_callback'] = function($query) use ($params){
            $request = request();
            // 按照名称进行搜索
            $query->where('type', 'consume') ;
            $query->where('status', 1) ;
            $query->where('refund_status','!=',2) ;
            $order_sn = $request->input('order_sn', '');
            if (!empty($order_sn)){
                $query->where('order_sn', $order_sn);
            }
            $card_no = $request->input('card_no', '');
            if (!empty($card_no)){
                $query->where('card_no', $card_no);
            }
            $pay_type = $request->input('pay_type', '');
            if (!empty($pay_type)){
                $query->where('pay_type', $pay_type);
            }
            $is_water = $request->input('is_water', -1);
            if ($is_water !=-1){
                $query->where('is_water', $is_water);
            }
            $status_end_day = $request->input('status_end_day', []);
            if (!empty($status_end_day)){
                [$status_time,$end_time] =  $status_end_day;
                $query->whereBetWeen('created_time', [strtotime($status_time. '00:00:00'), strtotime($end_time.' 23:59:59')]);
            }
        };
        return parent::lists($params); // TODO: Change the autogenerated stub
    }

    public function detailOrderConsume($params)
    {
        $order_info = $this->model->detail($params['order_id']);
        $order_money = number_format($order_info['buy_money'] - $order_info['amount']-$order_info['refund_price'],2);

        $res_junda = Consumption::GetPayConsumeByOrderNo($order_info['order_sn']);
        $refund_price=0;
        if ($res_junda['success']) {
            $IsConsumed = $res_junda['data']['IsConsumed'];
            if ($IsConsumed) {
                if ($order_info['refund_status'] == 0) {
                    $ConMoney = $res_junda['data']['ConMoney'];
                    $refund_price = number_format($order_info['buy_money'] - $ConMoney, 2);
                }
            } else {
                $refund_price = $order_info['buy_money'];
            }
        }else{
            $refund_price = $order_money;
        }

        return ['refund_price'=>$refund_price,'res_junda'=>$res_junda,'order_info'=>$order_info];
    }
    public function refundConsume($params)
    {
        if ($params['order_sn']){
            $order_info = $this->model->getWaterOrderByOrderSn($params['order_sn']) ;
        }else{
            $order_info = $this->model->detail($params['order_id']);
        }

        $amount = $order_info['amount'];
        $is_water = $order_info['is_water'];
        $pay_type = $order_info['pay_type'];
        $uddate_order = [
            'refund_type'=>$pay_type,
            'refund_time'=>time(),
            'refund_status'=>1,
            'operator_name'=>auth('admin')->user()->admin_name,
        ];

        $order_money = number_format($order_info['buy_money'] - $order_info['amount']-$order_info['refund_price'],2);
//        if ($order_money <= '0.00'){
//            $this->error='暂无退款金额';
//            return false;
//        }


        $order_id = $order_info['order_id'];
        $order_sn = $order_info['order_sn'];
        $refund_price = $params['refund_price'];
        $buy_money = $params['buy_money'];

        $res_junda = Consumption::GetPayConsumeByOrderNo($order_sn);


        if ($res_junda['success']){
            $JD_ConMoney = $res_junda['data']['ConMoney']*100;
            if ($JD_ConMoney==0){
                $refund_price = $amount;
                $uddate_order['amount']=0;
                $uddate_order['refund_status']=2;
            }else{
                $con_water = $res_junda['data']['ConWater']*1000;
                $uddate_order['con_water'] = $con_water;
            }

        }else{
            $refund_price = $amount;
            $uddate_order['amount']=0;
            $uddate_order['refund_status']=2;
        }

        $pay_type = $order_info['pay_type'];
        if ($pay_type == 'weixin' && $order_info['status'] == 1){
            // 微信
           $refund_res = PayWeChatApi::pay_refunds([
                'order_sn'=>$order_sn,
                'total'=>$buy_money,
                'refund_amount'=>$refund_price,
                'out_refund_no'=>time(),
            ]);
           if (isset($refund_res['code'])){
               $this->error=$refund_res['message'];
               return false;
           }
           $refund_prices = $order_info['refund_price'] + ($refund_res['amount']['payer_refund']/100);
        }elseif ($pay_type == 'alipay' && $order_info['status'] == 1){
            // 支付宝
            $refund_res =  AliPayService::instance()->refund($order_sn,$refund_price,$refund_price);
            if ($refund_res->code!=10000){
                $this->error=$refund_res->msg;
                return false;
            }
            $refund_prices = $order_info['refund_price'] + $refund_res->refundFee;
        }else{
            // 卡
           $card_info = UserCardModel::getInstance()->getUserByCardNo($order_info['card_no']);
            $refund_res=[];
        }
        $refund_info = OrderRefundModel::getInstance()->create([
            'user_id'=>$order_info['user_id'],
            'order_id'=>$order_id,
            'order_sn'=>$order_sn,
            'type'=>$pay_type,
            'refund_price'=>$refund_price,
            'refunded_time'=>date('Y-m-d H:i:s'),
            'desc'=>json_encode($refund_res),
            'operator_name'=>auth('admin')->user()->admin_name,
        ]);

        $uddate_order['refund_price'] =$refund_prices;
        $uddate_order['refund_id'] =$refund_info['refund_id']??0;
        $uddate_order['refund_desc'] =json_encode($refund_info);
        $this->model->updateWaterOrderByOrderId($order_id,$uddate_order);
        $this->error = '退款成功。累计退款金额：'.$refund_prices.'元';
        return true;

    }
}
